package com.rodvl.common.orm;



import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryComposition;
import org.springframework.data.repository.core.support.RepositoryFragment;

import javax.persistence.EntityManager;

import java.io.Serializable;

import static org.springframework.data.querydsl.QuerydslUtils.QUERY_DSL_PRESENT;

/**
 * JPA Repository工厂
 * 
 * @author liufang
 * 
 */
public class MyJpaRepositoryFactory extends JpaRepositoryFactory {

	private final EntityManager entityManager;

	public MyJpaRepositoryFactory(EntityManager entityManager) {
		super(entityManager);
		this.entityManager = entityManager;
	}

	@Override
	protected RepositoryComposition.RepositoryFragments getRepositoryFragments(RepositoryMetadata metadata) {
		RepositoryComposition.RepositoryFragments fragments = super.getRepositoryFragments(metadata);

		if (MyQueryDslJpaRepository.class.isAssignableFrom(
				metadata.getRepositoryInterface())) {

			JpaEntityInformation<?, Serializable> entityInformation =
					getEntityInformation(metadata.getDomainType());

			Object queryableFragment = getTargetRepositoryViaReflection(
					MyQueryDslJpaRepository.class, entityInformation, entityManager);

			fragments = fragments.append(RepositoryFragment.implemented(queryableFragment));
		}

		return fragments;
	}
}
